// 从cookie中获取存起来的用户名
var username = getCookie('username')
console.log(username);
if (username) {
    console.log('欢迎欢迎')
    $('.pagetop-content p').html(`
	汪，欢迎来天猫~
        <a href="userInfo.html" target="_Blank"  style="font-size:14px;">${username}</a> 用户
		<a onclick="logout()" target="_Blank">退出登录</a>
    `)
}

// 定义退出函数
function logout() {
    // 询问层
    layer.confirm('你确定要退出吗？', {
        btn: ['残忍离开', '考虑一下']
    }, function () {
        // 将内容还原
        $('.pagetop-content p').html(`
		汪，欢迎来天猫
			<a href="login.html" target="_Blank">请登录</a>
			<a href="register.html" target="_Blank">免费注册</a>
		`)
        // 删除cookie
        removeCookie('username')
        removeCookie('userId')
        localStorage.removeItem('token')
        layer.msg('退出成功', {
            icon: 1,
            time: 1500
        })
    }, function () {
        layer.msg('取消成功', {
            icon: 1,
            time: 1500
        })
    })
}

// 添加加载层
var loadId = layer.load(1, {
    shade: [1, '#000']
})

// 获取商品分类 - 发送ajax请求
$.get('http://localhost:8888/goods/category').then(res => {
    console.log(res);
    if (res.code === 1) {
        var html = ''
        res.list.forEach(item => {
            html += `
				<li class="li-One">
                    <i class="iconfont icon-nvzhuangneiyi red"></i>
                    <span><a href="#" class="red">${item}</a></span>
				</li>
			`
        })
        // 动态渲染数据
        $('.Sec-nav-main .ul-One').html(html)
        // 取消加载层
        layer.close(loadId)
        // 给li添加事件 - 利用事件委托
        $('.Sec-nav-main .ul-One .li-One').on('click', 'span', function () {
            // console.log(this);
            // 跳转 - 携带参数（当前点击分类的名称传递到列表页）
            location.href = 'shopList.html?category=' + $(this).text()
        })
    }
    lunbo()
    dingbu()
})

// 天猫超市渲染
var current = 4
var flag = true
var getdataFlag = true
getData1()

function getData1() {
    if (!flag) return false
    flag = false
    $.get('http://localhost:8888/goods/list', {
        pagesize: 6,
        current,

    }).then(res => {
        current++
        console.log(res);
        // var arr = res.list.filter(item => item.is_hot)
        // console.log(arr);
        if (!res.list.length) {
            getdataFlag = false
        }
        var html = ''
        res.list.forEach(item => {
            html += `
                <li>
					<div class="Sec-box">
						<a href="showShop.html?id=${item.goods_id}">
							<img src="${item.img_big_logo}">
							<p>${item.title}</p>
							<span>￥${item.current_price}</span>
						</a>
					</div>
				</li>
            `
        })
        $('.item-Four .right ul').html($('.item-Four .right ul').html() + html)
        flag = true
    })
    lunbo()
}

// 发送请求获取所有is_hot的商品并渲染到页面中
var current = 1
var flag = true
var getdataFlag = true
getData()

function getData() {
    if (!flag) return false
    flag = false
    $.get('http://localhost:8888/goods/list', {
        pagesize: 10,
        current,
        filter: 'hot'
    }).then(res => {
        current++
        console.log(res);
        // var arr = res.list.filter(item => item.is_hot)
        // console.log(arr);
        if (!res.list.length) {
            getdataFlag = false
        }
        var html = ''
        res.list.forEach(item => {
            html += `
                <li>
                    <div class="You-Likw-item">
                        <a href="showShop.html?id=${item.goods_id}">
                            <img src="${item.img_big_logo}">
                            <p>${item.title}</p>
                            <s>￥${item.price}</s>
                            <span>￥${item.current_price}</span>
                        </a>
                    </div>
                </li>
            `
        })
        $('.guess-You-Like .content ul').html($('.guess-You-Like .content ul').html() + html)


        flag = true
    })
    lunbo()
}


// 商品懒加载 - 监听滚动过的距离
window.onscroll = function () {
    if (getdataFlag) {
        // 获取滚动过的距离
        var w = document.documentElement.scrollTop || document.body.scrollTop
        var clientHeight = document.documentElement.clientHeight
        // 判断是否快到商品底部了
        if (w + clientHeight + 200 >= $('.guess-You-Like').offset().top + $('.guess-You-Like').height()) {
            getData()
        }
    }

}
//轮播函数
function lunbo() {
    var imgsPath = ['images/banner-1.jpg', 'images/banner-2.jpg', 'images/banner-3.jpg', 'images/banner-4.jpg', "images/banner-5.jpg"];
    var imgsColor = ['#4A0296', '#9A0CF4', '#E8E8E8', '#F8651F', '#E8E8E8'];
    var liArray = $(".banner-item ul li");
    var nowImgNum = 0;
    imgAutoMove();
    for (var i = 0; i < liArray.length; i++) {
        liArray[i].path = imgsPath[i];
        liArray[i].color = imgsColor[i];
        liArray[i].num = i;
    }

    //banner     鼠标移上去 设置背景颜色、图片路径
    liArray.mouseover(function () {

        $('.banner').css("background-color", this.color);
        $('#BannerImg').attr("src", this.path);


        $('#BannerImg').fadeIn(1000);
        nowImgNum = this.num;
        clearInterval(timer);
        $(liArray).css("background", "rgba(0, 0, 0, 0.2)");
        $(this).css('background', '#fff');
    })
    var liOneArray = $(".li-One");
    liOneArray.mouseover(function () {
        $(this).children(".Sec-nav-box").css("display", "block")
        var arry = $(this).children(".Sec-nav-box");
    })
    liOneArray.mouseout(function () {
        $(this).children(".Sec-nav-box").css("display", "none")
    })

    //定义计时器
    function autoRun() {
        return setInterval(imgAutoMove, 1500);
    }
    var timer = autoRun(); //调用定时器；
    //定时器    自动轮播图片
    $('#BannerImg').hover(function () {
        clearInterval(timer);
    }, function () {

        timer = autoRun();
    })
    //轮播函数
    function imgAutoMove() {
        if (nowImgNum > 4) nowImgNum = 0;

        $('.banner').css("background-color", imgsColor[nowImgNum]);
        $('#BannerImg').attr("src", imgsPath[nowImgNum]);

        $(liArray).css("background", "rgba(0, 0, 0, 0.2)");
        $(liArray[nowImgNum]).css("background", "#fff");
        nowImgNum++;
    }

}
// 点击搜索功能
// 点击搜索
// $('.search-submit').click(function(){
//     // 获取关键字
//     console.log(22);
//     var keywords = $(this).prev().val().trim()
//     if(keywords === ''){
//         return false
//     }
//     location.href = 'shopList.html?keywords='+keywords
// })
// 左侧导航
$(document).ready(function () {
    var $backToTop = $(".zuoce");
    /* 隐藏回顶部按钮 */
    $backToTop.hide();

    $(window).on('scroll', function () {
        if ($(this).scrollTop() > 100) {
            /* 返回顶部按钮将在用户向下滚动100像素后出现 */
            $backToTop.fadeIn();
        } else {
            $backToTop.fadeOut();
        }
    });
    
    $('.zuoce li:nth-child(1)').on('click', function (e) {
        $("html, body").animate({
            scrollTop: 700
        }, 500);
    });
    $('.zuoce li:nth-child(2)').on('click', function (e) {
        $("html, body").animate({
            scrollTop: 1390
        }, 500);
    });
    $('.zuoce li:nth-child(3)').on('click', function (e) {
        $("html, body").animate({
            scrollTop: 2100
        }, 500);
    });
    $('.zuoce li:nth-child(4)').on('click', function (e) {
        $("html, body").animate({
            scrollTop: 2800
        }, 500);
        
    });
    $('.zuoce li:nth-child(5)').on('click', function (e) {
        $("html, body").animate({
            scrollTop: 0
        }, 500);
    });
})
// 顶部导航
// function dingbu(){
//     let a = document.querySelector(".dingbu");
//     let A = document.querySelectorAll(".zcdh");
//     window.onscroll = function(){
//         let Obj = document.documentElement.scrollTop === 0? document.body:document.documentElement;
//         let gd = Obj.scrollTop;
//         if( gd > 1200){
//             a.style.top = "0";
//         }
//         else{
//             a.style.top = "-60px";
//             b.style.width = "0";
//         }
//     };
// }
